package com.fept.msgcore.msgserver.netty.handler;

/**
 * Created by Srma on 1/12/2017.
 */

import com.fept.msgcore.msgserver.netty.channel.ChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundMessageHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BaseMessageHandler extends ChannelInboundMessageHandlerAdapter<Object> {

    private static Logger logger = LoggerFactory.getLogger(BaseMessageHandler.class);
    private String name = "";
    private int readTimeout = 0;
    private int writeTimeout = 0;


    public String getName() {
        return this.name;
    }

    public BaseMessageHandler(String name) {
        this.name = name;
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel c = ctx.channel();
        logger.info(this.name + " channel active: " + c.id());
        ChannelManager.getChannelManager(this.name).addChannel(c.id().toString(), c);
    }

    public void channelInactive(ChannelHandlerContext ctx) {
        Channel c = ctx.channel();
        logger.info(this.name + "channel inactive: remove channel " + c.id());
        ChannelManager.getChannelManager(this.name).removeChannel(c.id().toString());
        ctx.close();
    }

    public void messageReceived(ChannelHandlerContext ctx, Object req) throws Exception {
        if(req != null) {
            logger.info(req.toString());
        }

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel c = ctx.channel();
        logger.info(this.name + "channel " + c.id() + " exception:" + cause.getMessage());
        c.close();
    }

    public int getReadTimeout() {
        return this.readTimeout;
    }

    public int getWriteTimeout() {
        return this.writeTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public void setWriteTimeout(int writeTimeout) {
        this.writeTimeout = writeTimeout;
    }


}
